package com.jjzhk.rpc.myutils;/**
 * HessionSerializationUtils
 *
 * @author : JJZHK
 * @date : 2016-09-03
 * @comments :
 **/

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;
import com.jjzhk.common.utils.SerializationUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class HessionSerializationUtils implements SerializationUtils {
    @Override
    public <T> byte[] serialize(T obj) {
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        Hessian2Output ho = new Hessian2Output(os);

        byte[] data = null;

        try {
            ho.startMessage();
            ho.writeObject(obj);

            ho.completeMessage();
            ho.close();
            data = os.toByteArray();
            os.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return data;
    }

    @Override
    public <T> T deserialize(byte[] data, Class<T> cls) {
        ByteArrayInputStream is = new ByteArrayInputStream(data);
        Hessian2Input hi = new Hessian2Input(is);
        T reObj = null;

        try {
            hi.startMessage();
            reObj =  (T) hi.readObject();
            hi.completeMessage();
            hi.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return reObj;
    }
}
